package com.meisupic.copyright.support.security;

import com.meisupic.copyright.service.IUserService;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.NullRememberMeServices;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * @Author lanjian
 * @Date 2018/4/14 下午8:37
 */
public class HuabanLoginFilter extends AbstractAuthenticationProcessingFilter {

  @Autowired
  protected IUserService userService;

  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    super.doFilter(req, res, chain);
  }

  private RememberMeServices rememberMeServices = new NullRememberMeServices();

  public HuabanLoginFilter() {
    super(new AntPathRequestMatcher("/huaban/login"));
  }

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request,
      HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    String sid = request.getParameter("sid");
    HuabanLoginAuthenticationToken authenticationToken = new HuabanLoginAuthenticationToken(sid,
        null);
    Authentication authentication = this.getAuthenticationManager().authenticate(authenticationToken);
    return authentication;
  }

  protected void successfulAuthentication(HttpServletRequest request,
      HttpServletResponse response, FilterChain chain, Authentication authResult)
      throws IOException {

    SecurityContextHolder.getContext().setAuthentication(authResult);

    rememberMeServices.loginSuccess(request, response, authResult);

    // Fire event
    if (this.eventPublisher != null) {
      eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
          authResult, this.getClass()));
    }
    response.sendRedirect("/index");
  }

}
